import type { TYPE } from "../pages/types";

export default class storage {
  private static data: TYPE.Data = {
    token: "",
    user: {
      id: 0,
      userName: "",
      password: "",
      name: "",
      phone: "",
      email: "",
      status: false,
      roleId: 0,
      remark: "",
      addTime: "",
    },
    menu: [],
    res: [],
    route: [],
    accessData: "",
  };
  /**
   * 保存app.tsx render函数参数，以实现在外部调用render函数。
   */
  static oldRender: Function;

  static getData() {
    if (this.data.token) return this.data;

    const dataText = sessionStorage.getItem("data");
    if (!dataText) return this.data;

    let data: TYPE.Data;
    try {
      data = JSON.parse(dataText);
    } catch(e) {
      console.log(e);
      return this.data;
    }

    return data;
  }

  static setData(newData: TYPE.Data) {
    this.data = newData;
    sessionStorage.setItem("data", JSON.stringify(newData));
    setTimeout(this.clear, 1000 * 60 * 60 * 24); // 一段时间后自动清除缓存
  }

  static clear() {
    this.data = {
      token: "",
      user: {
        id: 0,
        userName: "",
        password: "",
        name: "",
        phone: "",
        email: "",
        status: false,
        roleId: 0,
        remark: "",
        addTime: "",
      },
      menu: [],
      res: [],
      route: [],
      accessData: "",
    };
    sessionStorage.removeItem("data");
  }
};
